package com.lottery.im.module.chat.ui;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import butterknife.BindView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.ActiveInfo;
import com.lottery.im.api.result.entity.AdInfo;
import com.lottery.im.api.result.entity.SetTop;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.constant.Constants;
import com.lottery.im.constant.RxBusCode;
import com.lottery.im.constant.SpKeyConstant;
import com.lottery.im.module.chat.adapter.ConversationListAdapter;
import com.lottery.im.module.chat.adapter.ExtendHeaderAdapter;
import com.lottery.im.module.chat.presenter.ConversationListPresenter;
import com.lottery.im.module.chat.view.ConversationListView;
import com.lottery.im.module.main.ui.AgentWebViewActivity;
import com.lottery.im.module.tim.message.CustomMessage;
import com.lottery.im.module.tim.message.MessageFactory;
import com.lottery.im.module.tim.model.Conversation;
import com.lottery.im.module.tim.model.FriendshipConversation;
import com.lottery.im.module.tim.model.GroupManageConversation;
import com.lottery.im.module.tim.model.NomalConversation;
import com.lottery.im.module.tim.model.UnreadMessageTip;
import com.lottery.im.module.tim.presenter.ConversationPresenter;
import com.lottery.im.module.tim.presenter.FriendshipManagerPresenter;
import com.lottery.im.module.tim.presenter.GroupManagerPresenter;
import com.lottery.im.module.tim.utils.PushUtil;
import com.lottery.im.module.tim.viewfeatures.ConversationView;
import com.lottery.im.module.tim.viewfeatures.FriendshipMessageView;
import com.lottery.im.module.tim.viewfeatures.GroupManageMessageView;
import com.lottery.im.pop.ConversationMenuPopup;
import com.lottery.im.util.DisplayHelper;
import com.lottery.im.util.RelativePopupWindow;
import com.lottery.im.util.SPUtils;
import com.lottery.im.util.rxbus.RxBus;
import com.lottery.im.util.rxbus.Subscribe;
import com.lottery.im.widget.pullextend.ExtendListHeader;
import com.lottery.im.widget.pullextend.PullExtendLayoutForRecyclerView;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.ext.group.TIMGroupCacheInfo;
import com.tencent.imsdk.ext.group.TIMGroupPendencyItem;
import com.tencent.imsdk.ext.message.TIMManagerExt;
import com.tencent.imsdk.ext.sns.TIMFriendFutureItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import me.leolin.shortcutbadger.ShortcutBadger;

/*
 *  首页 消息 （会话列表）
 * */
public class ConversationListFragment extends BaseSwipeFragment<ConversationListPresenter>
    implements ConversationListView, ConversationView,
    FriendshipMessageView, GroupManageMessageView {

  @BindView(R.id.extend_recycler) PullExtendLayoutForRecyclerView mExtendRecycler;
  @BindView(R.id.list_conversation) RecyclerView mListView;
  @BindView(R.id.extend_header) ExtendListHeader mExtendHeader;

  private RecyclerView mListHeader;
  private ExtendHeaderAdapter mExtendHeaderAdapter;
  private List<ActiveInfo> mActiveInfos;
  private List<TIMUserProfile> mTIMUserProfiles = new ArrayList<>();
  private List<Conversation> mConversationList = new LinkedList<>();
  private ConversationListAdapter mAdapter;

  private ConversationPresenter mConversationPresenter;
  private FriendshipManagerPresenter mFriendshipManagerPresenter;
  private GroupManagerPresenter mGroupManagerPresenter;
  private List<String> mGroupList;
  private FriendshipConversation mFriendshipConversation;
  private GroupManageConversation mGroupManageConversation;
  // 保存的置顶信息
  private List<SetTop> mSetTops;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_conversation_list;
  }

  @Override protected void initPresenter() {
    presenter = new ConversationListPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {

    RxBus.get().register(this);
    getTopInfo();
    mExtendRecycler.setPullRefreshEnabled(false);
    mExtendRecycler.setPullLoadEnabled(false);
    mListHeader = mExtendHeader.getRecyclerView();

    mListHeader.setLayoutManager(
        new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));
    mActiveInfos = new ArrayList<>();
    mExtendHeaderAdapter = new ExtendHeaderAdapter(mActiveInfos);
    mExtendHeaderAdapter.setOnItemClickListener((adapter, view, position) -> {
      if (TextUtils.isEmpty(mActiveInfos.get(position).getUrl())) {
        showToast("暂无内容");
      } else {
        AgentWebViewActivity.create(mFragment, mActiveInfos.get(position).getUrl(),
            mActiveInfos.get(position).getName());
      }
    });
    mListHeader.setAdapter(mExtendHeaderAdapter);

    mListView.setLayoutManager(new LinearLayoutManager(mActivity));
    mAdapter = new ConversationListAdapter(mConversationList);
    mAdapter.setOnItemClickListener((adapter, view, position) -> {
      // item 点击
      mConversationList.get(position).navToDetail(mActivity);
      if (mConversationList.get(position) instanceof GroupManageConversation) {
        mGroupManagerPresenter.getGroupManageLastMessage();
      }
    });
    mAdapter.setOnItemLongClickListener((adapter, view, position) -> {
      if (!mConversationList.get(position).getIdentify().equals(Constants.SYSTEM_IDENTIFY)) {
        showLongClickMenu(view, position);
      }
      return true;
    });
    mAdapter.setEmptyView(getLayoutInflater().inflate(R.layout.layout_contact_empty, null));
    mListView.setAdapter(mAdapter);
    mFriendshipManagerPresenter = new FriendshipManagerPresenter(this);
    mGroupManagerPresenter = new GroupManagerPresenter(this);
    mConversationPresenter = new ConversationPresenter(this);
    mConversationPresenter.getConversation();

    presenter.getAd();
  }

  @Override public void getAdSuccess(AdInfo adInfo) {
    mActiveInfos.clear();
    if (null != adInfo && null != adInfo.getActiveList() && adInfo.getActiveList().size() > 0) {
      mActiveInfos.addAll(adInfo.getActiveList());
      mExtendRecycler.setPullRefreshEnabled(true);
    } else {
      mExtendRecycler.setPullRefreshEnabled(false);
    }
    mExtendHeaderAdapter.notifyDataSetChanged();
  }

  /**
   * 初始化界面或刷新界面
   */
  @Override public void initConversationView(List<TIMConversation> conversationList) {
    this.mConversationList.clear();
    mGroupList = new ArrayList<>();
    for (TIMConversation item : conversationList) {
      switch (item.getType()) {
        case C2C:
        case Group:
          this.mConversationList.add(new NomalConversation(item));
          mGroupList.add(item.getPeer());
          break;
      }
    }
    mFriendshipManagerPresenter.getFriendshipLastMessage();
    mGroupManagerPresenter.getGroupManageLastMessage();
    getUsersProfile();
  }

  /**
   * 如果有非好友用户会话列表，则需要去刷新用户资料数据
   */
  public void getUsersProfile() {

    for (int i = 0; i < mConversationList.size(); i++) {
      for (TIMUserProfile timUserProfile : mTIMUserProfiles) {
        if (mConversationList.get(i).getIdentify().equals(timUserProfile.getIdentifier())) {
          mConversationList.get(i).setName(timUserProfile.getNickName());
          mConversationList.get(i).setAvatar(timUserProfile.getFaceUrl());
          mAdapter.notifyItemChanged(i);
          break;
        }
      }
    }

    List<String> ids = new ArrayList<>();
    for (Conversation conversation : mConversationList) {
      if (conversation.getType() == TIMConversationType.C2C && conversation.getName()
          .equals(conversation.getIdentify())) {
        ids.add(conversation.getIdentify());
      }
    }

    if (ids.size() > 0) {
      presenter.getUsersProfile(ids);
    }
  }

  @Override public void addUsersProfile(List<TIMUserProfile> timUserProfiles) {
    if (null != timUserProfiles) {
      mTIMUserProfiles.addAll(timUserProfiles);
    }
    for (int i = 0; i < mConversationList.size(); i++) {
      for (TIMUserProfile timUserProfile : mTIMUserProfiles) {
        if (mConversationList.get(i).getIdentify().equals(timUserProfile.getIdentifier())) {
          mConversationList.get(i).setName(timUserProfile.getNickName());
          mConversationList.get(i).setAvatar(timUserProfile.getFaceUrl());
          mAdapter.notifyItemChanged(i);
          break;
        }
      }
    }
  }

  /**
   * 更新最新消息显示
   *
   * @param message 最后一条消息
   */
  @Override
  public void updateMessage(TIMMessage message) {
    if (message == null) {
      setListTop();
      mAdapter.notifyDataSetChanged();
      getUsersProfile();
      return;
    }
    if (message.getConversation().getType() == TIMConversationType.System) {
      mGroupManagerPresenter.getGroupManageLastMessage();
      return;
    }
    if (MessageFactory.getMessage(message) instanceof CustomMessage) return;
    NomalConversation conversation = new NomalConversation(message.getConversation());
    Iterator<Conversation> iterator = mConversationList.iterator();
    while (iterator.hasNext()) {
      Conversation c = iterator.next();
      if (conversation.equals(c)) {
        conversation = (NomalConversation) c;
        iterator.remove();
        break;
      }
    }
    conversation.setLastMessage(MessageFactory.getMessage(message));
    mConversationList.add(conversation);
    refresh();
  }

  /**
   * 更新好友关系链消息
   */
  @Override
  public void updateFriendshipMessage() {
    mFriendshipManagerPresenter.getFriendshipLastMessage();
  }

  /**
   * 删除会话
   */
  @Override
  public void removeConversation(String identify) {
    Iterator<Conversation> iterator = mConversationList.iterator();
    while (iterator.hasNext()) {
      Conversation conversation = iterator.next();
      if (conversation.getIdentify() != null && conversation.getIdentify().equals(identify)) {
        iterator.remove();
        setListTop();
        mAdapter.notifyDataSetChanged();
        getUsersProfile();
        return;
      }
    }
  }

  @Override public void removeAndConversation(TIMConversationType type, String identify) {
    removeConversation(identify);
    TIMManagerExt.getInstance().deleteConversation(type, identify);
  }

  /**
   * 更新群信息
   */
  @Override
  public void updateGroupInfo(TIMGroupCacheInfo info) {
    for (Conversation conversation : mConversationList) {
      if (conversation.getIdentify() != null && conversation.getIdentify()
          .equals(info.getGroupInfo().getGroupId())) {
        setListTop();
        mAdapter.notifyDataSetChanged();
        return;
      }
    }
  }

  /**
   * 刷新
   */
  @Override
  public void refresh() {
    Collections.sort(mConversationList);
    setListTop();
    mAdapter.notifyDataSetChanged();
    getUsersProfile();
    ShortcutBadger.applyCount(MyApplication.getInstance(), getTotalUnreadNum());
    UnreadMessageTip tip = new UnreadMessageTip();
    tip.setPosition(0);
    tip.setNum(getTotalUnreadNum());
    RxBus.get().send(RxBusCode.UNREAD_NUM_CODE, tip);
  }

  /**
   * 获取好友关系链管理系统最后一条消息的回调
   *
   * @param message 最后一条消息
   * @param unreadCount 未读数
   */
  @Override
  public void onGetFriendshipLastMessage(TIMFriendFutureItem message, long unreadCount) {
    if (mFriendshipConversation == null) {
      mFriendshipConversation = new FriendshipConversation(message);
    } else {
      mFriendshipConversation.setLastMessage(message);
    }
    mFriendshipConversation.setUnreadCount(unreadCount);

    /*
    *
    //是否把 "新朋友"（即最近添加好友的提示）显示到消息列表
    if (!mConversationList.contains(mFriendshipConversation)) {
      mConversationList.add(mFriendshipConversation);
    }
     * */
    setFriendAndGroupUnreadNum();
    refresh();
  }

  /**
   * 获取好友关系链管理最后一条系统消息的回调
   *
   * @param message 消息列表
   */
  @Override
  public void onGetFriendshipMessage(List<TIMFriendFutureItem> message) {
    mFriendshipManagerPresenter.getFriendshipLastMessage();
  }

  /**
   * 获取群管理最后一条系统消息的回调
   *
   * @param message 最后一条消息
   * @param unreadCount 未读数
   */
  @Override
  public void onGetGroupManageLastMessage(TIMGroupPendencyItem message, long unreadCount) {
    if (mGroupManageConversation == null) {
      mGroupManageConversation = new GroupManageConversation(message);
      /*
      *
      // 是否显示群组消息（不是群消息，比如：申请加群验证）
      mConversationList.add(mGroupManageConversation);
      * */
    } else {
      mGroupManageConversation.setLastMessage(message);
    }
    mGroupManageConversation.setUnreadCount(unreadCount);
    setFriendAndGroupUnreadNum();
    refresh();
  }

  /**
   * 获取群管理系统消息的回调
   *
   * @param message 分页的消息列表
   */
  @Override
  public void onGetGroupManageMessage(List<TIMGroupPendencyItem> message) {

  }

  // 未读消息 总数
  private int getTotalUnreadNum() {
    int num = 0;
    for (Conversation conversation : mConversationList) {
      num += conversation.getUnreadNum();
    }
    return num;
  }

  // 验证通知包含：好友验证 + 群组验证
  private void setFriendAndGroupUnreadNum() {
    int friendUnreadNum = 0, groupUnreadNum = 0;
    if (null != mFriendshipConversation) {
      friendUnreadNum = (int) mFriendshipConversation.getUnreadNum();
    }
    if (null != mGroupManageConversation) {
      groupUnreadNum = (int) mGroupManageConversation.getUnreadNum();
    }

    UnreadMessageTip tip = new UnreadMessageTip();
    tip.setPosition(1);
    tip.setNum(friendUnreadNum + groupUnreadNum);
    RxBus.get().send(RxBusCode.UNREAD_NUM_CODE, tip);
  }

  // 长按菜单
  private void showLongClickMenu(View view, int itemPosition) {
    mAdapter.setLongClickPosition(itemPosition);
    ConversationMenuPopup menuFilterPopup = new ConversationMenuPopup(mContext);
    List<String> items = new ArrayList<>();

    boolean isTop = false;

    if (null != mSetTops) {
      for (SetTop setTop : mSetTops) {
        if (setTop.getId().equals(mConversationList.get(itemPosition).getIdentify())
            && setTop.getUserId().equals(MyApplication.getInstance().getUserInfo().getUserId())
            ) {
          isTop = true;
          break;
        }
      }
    }
    if (isTop) {
      items.add("取消置顶");
    } else {
      items.add("置顶");
    }

    items.add("删除");
    menuFilterPopup.setDataSelect(items,
        (adapter, view1, position) -> {

          Conversation conversation = mConversationList.get(itemPosition);

          switch (position) {
            case 0:
              if (items.get(0).equals("置顶")) {
                // 置顶
                SetTop setTop = new SetTop();
                setTop.setUserId(MyApplication.getInstance().getUserInfo().getUserId());
                setTop.setId(conversation.getIdentify());
                setTop.setTime(System.currentTimeMillis());
                mSetTops.add(setTop);
              } else {
                // 取消置顶
                for (int i = 0; i < mSetTops.size(); i++) {
                  if (mSetTops.get(i).getId().equals(conversation.getIdentify())) {
                    mSetTops.remove(i);
                    break;
                  }
                }
              }
              setTopInfo();
              break;
            case 1:
              // 删除
              conversation.deleteConversationAndLocalMsgs();
              break;
          }
        });

    float y = view.getY();
    int screenHeight = DisplayHelper.getScreenHeight(mActivity);
    if (y > screenHeight * 1 / 2) {
      menuFilterPopup.showOnAnchor(view, RelativePopupWindow.VerticalPosition.ABOVE,
          RelativePopupWindow.HorizontalPosition.CENTER, 0, 50);
    } else {
      menuFilterPopup.showOnAnchor(view, RelativePopupWindow.VerticalPosition.BELOW,
          RelativePopupWindow.HorizontalPosition.CENTER, 0, -50);
    }
    menuFilterPopup.setOnDismissListener(() -> mAdapter.cancelLongClickPosition(itemPosition));
  }

  /**
   * 获取保存的置顶信息
   */
  private void getTopInfo() {
    String setTopInfo =
        (String) SPUtils.get(MyApplication.getInstance(), SpKeyConstant.SET_TOP_KEY, "");
    mSetTops = new Gson().fromJson(setTopInfo, new TypeToken<List<SetTop>>() {
    }.getType());
    if (null == mSetTops) {
      mSetTops = new ArrayList<>();
    }
  }

  /**
   * 保存置顶信息
   */
  private void setTopInfo() {
    SPUtils.put(MyApplication.getInstance(), SpKeyConstant.SET_TOP_KEY,
        new Gson().toJson(mSetTops));
    getTopInfo();
    setListTop();
    mAdapter.notifyDataSetChanged();
    getUsersProfile();
  }

  private long getSetTopTime(String id) {
    if (null != mSetTops && mSetTops.size() > 0) {

      for (SetTop setTop : mSetTops) {
        if (setTop.getId().equals(id) && setTop.getUserId()
            .equals(MyApplication.getInstance().getUserInfo().getUserId())) {
          return setTop.getTime();
        }
      }
    }
    return 0;
  }

  /**
   * 根据保存的置顶信息，调整adapter的顺序
   */
  private void setListTop() {
    Collections.sort(mConversationList);
    if (null != mSetTops && mSetTops.size() > 0) {
      List<Conversation> topConversations = new ArrayList<>();
      List<Conversation> normalConversations = new ArrayList<>();
      for (Conversation conversation : mConversationList) {
        for (SetTop setTop : mSetTops) {
          if (setTop.getId().equals(conversation.getIdentify())
              && setTop.getUserId().equals(MyApplication.getInstance().getUserInfo().getUserId())) {
            topConversations.add(conversation);
            break;
          }
        }
        if (!topConversations.contains(conversation)) {
          normalConversations.add(conversation);
        }
      }
      Collections.sort(topConversations,
          (o1, o2) -> (int) (getSetTopTime(o2.getIdentify()) - getSetTopTime(o1.getIdentify())));
      mConversationList.clear();
      mConversationList.addAll(topConversations);
      mConversationList.addAll(normalConversations);
      mAdapter.setSettopId(mSetTops);
      getUsersProfile();
    } else {
      mAdapter.setSettopId(null);
    }
  }

  @Override public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
    if (!hidden) {
      refresh();
      PushUtil.getInstance().reset();
    }
  }

  @Override public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
      refresh();
      PushUtil.getInstance().reset();
    }
  }

  @Override
  public void onResume() {
    super.onResume();
    refresh();
    PushUtil.getInstance().reset();
  }

  /**
   * onResume 通知
   */
  @Subscribe(code = RxBusCode.ONRESUME_CODE)
  public void refreshOnResume() {
    refresh();
    PushUtil.getInstance().reset();
  }

  @Override protected boolean canDragBack() {
    return false;
  }

  @Override public void onDestroyView() {
    super.onDestroyView();
    RxBus.get().unRegister(this);
    mConversationPresenter.stop();
  }
}
